﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Threading;
using Glue.Lib;
using Glue.Lib.Servers;

namespace SqueezeboxBridge
{
    public class StreamServer 
    {
        private const string _whName = "Global\\SqueezeBoxBridge_w{E9EFBF72-F28C-4A34-8E03-0A4ADF31DB93}";

        public static bool Start()
        {
            // start up StreamServer
            bool createdNew = false;
            EventWaitHandle evw = new EventWaitHandle(false, EventResetMode.AutoReset, _whName, out createdNew);
            if (createdNew)
            {
                // OK, no other instance, start up the server
                Log.Debug("StreamServer starting...");
                Thread th = new Thread(new ParameterizedThreadStart(StartThreadProc));
                th.Start();

                return true;
            }
            else
            {
                // Mutex already exists
                Log.Debug("StreamServer already running, can't start second instance.");

                return false;
            }
        }

        private static void StartThreadProc(object data)
        {
            // start the streamserver
            InternalStreamServer streamServer;
            streamServer = new InternalStreamServer(new IPEndPoint(IPAddress.Any, 9091));
            streamServer.Start();

            // now wait for the signal to stop again...
            bool createdNew;
            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset, _whName, out createdNew);

            // now wait
            while (!ewh.WaitOne(1000))
            {
                //Log.Debug("Waiting and serving...");
            }

            // Signal received, stop server
            streamServer.Stop();

            while (!streamServer.Stopped)
            {
                Thread.Sleep(1000);
            }

            Log.Debug("StreamServer stopped.");
        }

        public static bool Stop()
        {
            bool createdNew;
            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset, _whName, out createdNew);

            // new wait handle?
            if (!createdNew)
            {
                // signal handle 
                Log.Debug("StreamServer stopping...");
                ewh.Set();

                return true;
            }
            else
            {
                Log.Debug("StreamServer not running, so can't stop.");

                return false;
            }
        }
    }
}
